<template>
    <div class="search-box">
        <el-form
            ref="formRef"
            :model="modelValue"
            :inline="true"
            :label-width="labelWidth"
            :label-position="labelPosition"
            :size="size"
            :disabled="disabled"
            @submit.prevent
        >
            <el-row :gutter="20">
                <template v-for="(item, index) in fixedFields" :key="index">
                    <el-col :span="item.span || span || 6">
                        <el-form-item
                            :label="item.label"
                            :prop="item.prop"
                            :rules="item.rules"
                        >
                            <!-- 输入框 -->
                            <el-input
                                v-if="item.type === 'input'"
                                :model-value="modelValue[item.prop]"
                                @update:model-value="(val) => updateValue(item.prop, val)"
                                :placeholder="item.placeholder"
                                :disabled="item.disabled"
                                :clearable="item.clearable"
                                :maxlength="item.maxlength"
                                :minlength="item.minlength"
                                :show-word-limit="item.showWordLimit"
                            />

                            <!-- 下拉选择 -->
                            <el-select
                                v-else-if="item.type === 'select'"
                                :model-value="modelValue[item.prop]"
                                @update:model-value="(val) => updateValue(item.prop, val)"
                                :placeholder="item.placeholder"
                                :disabled="item.disabled"
                                :clearable="item.clearable"
                                :filterable="item.filterable"
                                :multiple="item.multiple"
                                :collapse-tags="item.collapseTags"
                                :collapse-tags-tooltip="item.collapseTagsTooltip"
                            >
                                <el-option
                                    v-for="option in item.options"
                                    :key="option.value"
                                    :label="option.label"
                                    :value="option.value"
                                    :disabled="option.disabled"
                                />
                            </el-select>

                            <!-- 日期选择 -->
                            <el-date-picker
                                v-else-if="item.type === 'date'"
                                :model-value="modelValue[item.prop]"
                                @update:model-value="(val) => updateValue(item.prop, val)"
                                :type="item.dateType"
                                :placeholder="item.placeholder"
                                :disabled="item.disabled"
                                :clearable="item.clearable"
                                :format="item.format"
                                :value-format="item.valueFormat"
                                :start-placeholder="item.startPlaceholder"
                                :end-placeholder="item.endPlaceholder"
                                :range-separator="item.rangeSeparator"
                            />
                        </el-form-item>
                    </el-col>
                </template>

                <el-col :span="6">
                    <el-form-item class="button-group">
                        <el-button
                            type="primary"
                            :loading="loading"
                            @click="handleSearch"
                        >
                            搜索
                        </el-button>
                        <el-button
                            v-if="isShowResetBtn"
                            @click="handleReset"
                        >
                            重置
                        </el-button>
                        <el-button
                            v-if="hasAdvancedFields"
                            type="text"
                            @click="toggleAdvanced"
                        >
                            {{ isShowAllFields ? '收起' : '展开' }}
                            <el-icon>
                                <component :is="isShowAllFields ? 'ArrowUp' : 'ArrowDown'" />
                            </el-icon>
                        </el-button>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row v-if="isShowAllFields" :gutter="20">
                <template v-for="(item, index) in advancedFields" :key="index">
                    <el-col :span="item.span || span || 6">
                        <el-form-item
                            :label="item.label"
                            :prop="item.prop"
                            :rules="item.rules"
                        >
                            <!-- 输入框 -->
                            <el-input
                                v-if="item.type === 'input'"
                                :model-value="modelValue[item.prop]"
                                @update:model-value="(val) => updateValue(item.prop, val)"
                                :placeholder="item.placeholder"
                                :disabled="item.disabled"
                                :clearable="item.clearable"
                                :maxlength="item.maxlength"
                                :minlength="item.minlength"
                                :show-word-limit="item.showWordLimit"
                            />

                            <!-- 下拉选择 -->
                            <el-select
                                v-else-if="item.type === 'select'"
                                :model-value="modelValue[item.prop]"
                                @update:model-value="(val) => updateValue(item.prop, val)"
                                :placeholder="item.placeholder"
                                :disabled="item.disabled"
                                :clearable="item.clearable"
                                :filterable="item.filterable"
                                :multiple="item.multiple"
                                :collapse-tags="item.collapseTags"
                                :collapse-tags-tooltip="item.collapseTagsTooltip"
                            >
                                <el-option
                                    v-for="option in item.options"
                                    :key="option.value"
                                    :label="option.label"
                                    :value="option.value"
                                    :disabled="option.disabled"
                                />
                            </el-select>

                            <!-- 日期选择 -->
                            <el-date-picker
                                v-else-if="item.type === 'date'"
                                :model-value="modelValue[item.prop]"
                                @update:model-value="(val) => updateValue(item.prop, val)"
                                :type="item.dateType"
                                :placeholder="item.placeholder"
                                :disabled="item.disabled"
                                :clearable="item.clearable"
                                :format="item.format"
                                :value-format="item.valueFormat"
                                :start-placeholder="item.startPlaceholder"
                                :end-placeholder="item.endPlaceholder"
                                :range-separator="item.rangeSeparator"
                            />
                        </el-form-item>
                    </el-col>
                </template>
            </el-row>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { FormInstance } from 'element-plus'
import type { UnionFormConfigType } from '../MagicForm/types/UnionFormConfigType'

const props = defineProps<{
    modelValue: Record<string, any>
    fields: UnionFormConfigType[]
    loading?: boolean
    isShowResetBtn?: boolean
    isShowAllFields?: boolean
    searchKey?: string
    cacheIdentifer?: string
    labelWidth?: string
    labelPosition?: 'left' | 'right' | 'top'
    size?: 'large' | 'default' | 'small'
    disabled?: boolean
    gutter?: number
    span?: number
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: Record<string, any>): void
    (e: 'search-change', value: Record<string, any>): void
    (e: 'field-change', value: Record<string, any>): void
    (e: 'reset', value: Record<string, any>): void
}>()

const formRef = ref<FormInstance>()
const isShowAllFields = ref(props.isShowAllFields || false)

// 计算属性：固定显示的字段
const fixedFields = computed(() => {
    return props.fields.filter(item => item.isFixed)
})

// 计算属性：高级搜索字段
const advancedFields = computed(() => {
    return props.fields.filter(item => !item.isFixed)
})

// 计算属性：是否有高级搜索字段
const hasAdvancedFields = computed(() => {
    return props.fields.some(item => !item.isFixed)
})

// 更新表单值
const updateValue = (prop: string, value: any) => {
    emit('update:modelValue', {
        ...props.modelValue,
        [prop]: value
    })
    emit('field-change', {
        ...props.modelValue,
        [prop]: value
    })
}

// 切换高级搜索
const toggleAdvanced = () => {
    isShowAllFields.value = !isShowAllFields.value
}

// 搜索
const handleSearch = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            emit('search-change', props.modelValue)
        }
    })
}

// 重置
const handleReset = () => {
    formRef.value?.resetFields()
    emit('reset', {})
}

// 暴露方法
defineExpose({
    validate: () => formRef.value?.validate(),
    resetFields: () => formRef.value?.resetFields(),
    clearValidate: () => formRef.value?.clearValidate()
})
</script>

<style lang="less" scoped>
.search-box {
    padding: 20px;
    background-color: var(--el-bg-color);
    border-radius: 4px;
    box-shadow: var(--el-box-shadow-light);

    :deep(.el-form) {
        width: 100%;
    }

    :deep(.el-form-item) {
        margin-bottom: 0;
    }

    :deep(.el-button--text) {
        padding: 0 10px;
    }
}
</style>
